package cc.mrbird.febs.common.datasource.starter.organization;

import com.xf.common.core.constant.CommonConstants;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 必须要先等Security Filter 先执行，将token解析出登录用户，因次order 大小，需要大点
 *
 * @author 豆沙包
 * @date 2018/9/13
 */
@Slf4j
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class OrganizationContextHolderFilter extends GenericFilterBean {

    @Override
    @SneakyThrows(Exception.class)
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String organizationId = request.getHeader(CommonConstants.ORGANIZATION_ID);
        String paramOrganizationId = request.getParameter(CommonConstants.ORGANIZATION_ID);
        String organizationFlagStr = request.getHeader(CommonConstants.ORGANIZATION_FLAG);
        Boolean organizationFlag = organizationFlagStr == null || Boolean.parseBoolean(organizationFlagStr);
        organizationId = "bbt";
        try {
            if (StringUtils.isNotBlank(organizationId)) {
                OrganizationContextHolder.setOrganizationConfig(organizationId, organizationFlag);

            } else if (StringUtils.isNotBlank(paramOrganizationId)) {
                OrganizationContextHolder.setOrganizationConfig(paramOrganizationId, organizationFlag);
            } else {
                OrganizationContextHolder.setOrganizationConfig(CommonConstants.ORGANIZATION_ID_1, organizationFlag);

            }
        } catch (Exception e) {
            OrganizationContextHolder.setOrganizationConfig(CommonConstants.ORGANIZATION_ID_1, organizationFlag);
        }


        filterChain.doFilter(request, response);
        OrganizationContextHolder.clear();
    }

}
